package com.gin.kotlin.no_gay_alliance.webview

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import android.content.res.Resources.Theme
import android.util.AttributeSet
import android.view.ViewGroup
import android.webkit.WebView
import android.widget.FrameLayout
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.FragmentActivity
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.enums.NgaTheme
import com.gin.kotlin.no_gay_alliance.store.GlobalProperty
import com.gin.nga.bbscode.BbsCodeNode
import com.gin.nga.utils.BbsCodeRenderer
import com.wgw.photo.preview.Config
import com.wgw.photo.preview.IndicatorType
import java.time.ZonedDateTime

/**
 * 渲染论坛代码的WebView
 * @property busy Boolean
 * @property timestamp (ZonedDateTime..ZonedDateTime?)
 * @property content String
 */
@SuppressLint("SetJavaScriptEnabled")
class BbsCodeWebView : WebView {
    private var activity: FragmentActivity = context as FragmentActivity

    /**
     * 模板
     */
    var template = ""

    /**
     * 当前WebView是否繁忙
     */
    var busy = false

    var renderer: BbsCodeRenderer? = null

    /**
     * 创建时间
     */
    private var timestamp = ZonedDateTime.now()

    var content = ""

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)

    init {
        //禁用滚动条
        isVerticalScrollBarEnabled = false
        isHorizontalScrollBarEnabled = false
        //背景透明
        setBackgroundColor(0)

        layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

        // 向WebView中的网页暴露方法接口
//        addJavascriptInterface(this, "android")

        //设置WebView属性,运行执行js脚本
        settings.javaScriptEnabled = true
        //默认字体大小14
        settings.defaultFontSize = 14
        // 阻止图片自动加载
//        settings.blockNetworkImage = true
    }

    fun loadDataWithBaseURL(data: String) {
        if (data == content) return
        content = data
        // 设置为忙碌中
        val baseUrl = "https://${GlobalProperty.getInstance().domain.host}"

        super.loadDataWithBaseURL(baseUrl, data, "text/html", "UTF-8", null)
    }

    fun loadTimestamp() {
        loadDataWithBaseURL("<div>$timestamp</div>")
    }
    
    /**
     * 加载论坛代码节点列表
     * @param bbsCodeNode List<BbsCodeNode>?
     */
    fun load(bbsCodeNode: List<BbsCodeNode>?,isWarden:Boolean=false) {
        val globalProperty = GlobalProperty.getInstance()
        // 系统当前是否处于深色模式
        val systemUiModeNight = resources.configuration.uiMode.and(Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
        // 系统当前主题
        val theme = if (systemUiModeNight && globalProperty.themeFollow) NgaTheme.BLACK else globalProperty.theme
        // 根据主题决定顶层class
        val bodyClass = when (isWarden) {
            true -> if (theme == NgaTheme.BLACK) "black_warden_text_color" else "warden_text_color"
            false -> if (theme == NgaTheme.BLACK) "black_text_color" else "default_text_color"
        }

        // 渲染节点
        val content = renderer?.render(bbsCodeNode) ?:return

        // 加载渲染
        loadDataWithBaseURL(template.replace("[根CLASS占位]", bodyClass).replace("[回复容器占位]", content))
    }

    private fun previewConfig(): Config {
        val resources: Resources = context.resources
        val theme: Theme = context.theme

        val config = Config()
        //图片指示器类型(目前只有圆点和文本)，预览>=2张图片时有效
        config.indicatorType = IndicatorType.DOT
        // indicatorType为DOT时，设置DOT最大数量，如果sources数量超过此值，则改用IndicatorType.TEXT
        config.maxIndicatorDot = 9
        // 指示当前预览界面指示器颜色
        config.selectIndicatorColor = ResourcesCompat.getColor(resources, R.color.yellow_dark, theme)
        // 非当前预览界面指示器颜色
        config.normalIndicatorColor = ResourcesCompat.getColor(resources, R.color.yellow_light, theme)
        // 图片加载loading color, android5.0(含)之后有效
        config.progressColor = ResourcesCompat.getColor(resources, R.color.yellow_dark, theme)
        // 全屏预览
        config.fullScreen = true
        // 是否展示缩略图蒙层，如果设置为true,则预览动画执行时,缩略图不显示，预览更沉浸
        config.showThumbnailViewMask = true
        // 是否在打开预览动画执行开始的时候执行状态栏隐藏/显示操作
        config.openAnimStartHideOrShowStatusBar = true
        // 动画时间，null：使用默认时间，<=0: 不执行动画
        config.animDuration = 400L
        return config
    }

    companion object {
        private val TAG = BbsCodeWebView::class.java.simpleName


    }
}